<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Main extends CI_Controller {

    private $_data = '';

    function __construct() {
        parent::__construct();
        $this->load->helper(array('frontend', 'time'));
        
        $this->load->model(array('boothmodel', 'booth_products_model', 'admodel',
            'booth_product_comment_model', 'ad_comment_model', 'eventmodel', 'generalmodel'));
        $data['left_event'] = $this->eventmodel->getEvents(2, 0);
        $this->load->view('layout/frontend/element/fixed-left-bar.php', $data, true);
    }

    public function index($page = 0, $isAjax = FALSE) {
        $this->load->library('form_validation');
        $this->load->helper('frontend_helper');
        $this->load->helper('frontend');
        $this->load->helper('booth');
        $this->load->helper('ads');
        $this->load->helper('controller');

        $data['banner'] = $this->generalmodel->get();
        
        // Lấy tối đa 9 gian hàng có sản phẩm
        $booth = $this->boothmodel->getBoothHasProducts(9, $page * 9);
        if (isset($booth[0]) && $booth[0] != "") {
            // Nếu có gian hàng thì lấy 1 sản phẩm bất kỳ
            for ($i = 0; $i < 9; $i++) {
                if (count($booth) == $i) {
                    $booth[$i] = $booth[$i - 1];
                }
                $booth_product = $this->booth_products_model->getOneBoothProductByBoothId($booth[$i]['id']);
                $booth[$i]['product_id'] = $booth_product['id'];
                $booth[$i]['product_slug'] = $booth_product['slug'];
                $booth[$i]['type'] = 'booth';
                $booth[$i]['rate'] = $booth_product['rate'];
                $count_comment = $this->booth_product_comment_model->getCountCommentByBoothProductId($booth[$i]['product_id']);
                $booth[$i]['count_comment'] = $count_comment['count'];

                $event = $this->eventmodel->getEventByCidAndType($booth[$i]['id'], 2);
                $booth[$i]['event'] = $event;
            }
        }

        // Lấy tối đa 9 rao vặt
        $ad = $this->admodel->getListAdLimit(9, $page * 9);
        if (isset($ad[0]) && $ad[0] != "") {
            // Nếu có rao vặt
            for ($i = 0; $i < 9; $i++) {
                if (count($ad) == $i) {
                    $ad[$i] = $ad[$i - 1];
                }
                $ad[$i]['type'] = 'ad';
                $count_comment = $this->ad_comment_model->getCountCommentByAdId($ad[$i]['ad_id']);
                $ad[$i]['count_comment'] = $count_comment['count'];
            }
        }

        $results = "";
        for ($i = 0; $i < 18; $i++) {
            if ($i % 2 == 0) {
                $results[$i] = $booth[(int) $i / 2];
            } else {
                $results[$i] = $ad[(int) $i / 2];
            }
        }
        $data['results'] = $results;

        // Lấy 6 sản phẩm bất kì cho slider
        $data['products'] = $this->booth_products_model->getRandomProducts(array('limit' => 6));

        if ($isAjax) {
          $data['extra'] = TRUE;
          $this->load->view('main/index', $data);
        } else {
          $this->_data['content'] = $this->load->view('main/index', $data, true);
          $this->load->view('layout/frontend/main', $this->_data);
        }
    }

    public function general() {
        $this->load->helper('frontend');
        $this->load->library(array('form_validation'));
        $data['types'] = array(
            '1' => 'Banner 1',
            '2' => 'Banner 2',
            '3' => 'Banner 3',
            '4' => 'Banner 4',
            '5' => 'Banner 5',
            '6' => 'Banner 6',
        );
        $data['smalls'] = array(
            '7' => 'Banner 7',
            '8' => 'Banner 8',
            '9' => 'Banner 9',
        );
        $data['banner'] = $this->generalmodel->get();
        $this->load->helper('frontend');
        $this->_data['content'] = $this->load->view('main/general', $data, true);
        $this->load->view('layout/frontend/index', $this->_data);
    }

    public function ajaxUpload() {
        error_reporting(0);
        $max_filesize = 2097152;
        // Maximum filesize in BYTES.
        $allowed_filetypes = array('.jpg', '.jpeg', '.gif', '.png');
        // These will be the types of file that will pass the validation.
        $filename = $_FILES['userfile']['name'];
        // Get the name of the file (including file extension).
        $ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
        // Get the extension from the filename.
        $file_strip = str_replace(" ", "_", $filename);
        //Strip out spaces in filename
        $upload_path = 'upload/general/';
        //Set upload path
        // Check if the filetype is allowed, if not DIE and inform the user.
        if (!in_array($ext, $allowed_filetypes)) {
            die('<div class="error">File không hợp lệ. Hãy chọn file khác!</div>');
        }
        // Now check the filesize, if it is too large then DIE and inform the user.
        if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
            die('<div class="error">File quá lớn. Hãy chọn file khác!</div>');
        }
        // Check if we can upload to the specified path, if not DIE and inform the user.
        if (!is_writable($upload_path)) {
            die('<div class="error">Upload không thành công. Vui lòng check lại permission!</div>');
        }
        // Move the file if eveything checks out.
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $file_strip)) {
            echo json_encode(array('link' => base_url($upload_path . $file_strip), 'file' => $file_strip));
            // It worked.
        } else {
            echo '<div class="error">Upload không thành công. Hãy chọn file khác!</div>';
            // It failed :(.
        }
    }

    public function uploadFile() {
        $image = $_POST['image'];
        $url = $_POST['url'];
        $title1 = isset($_POST['title1']) ? $_POST['title1'] : '' ;
        $title2 = isset($_POST['title2']) ? $_POST['title2'] : '' ;
        $title3 = isset($_POST['title3']) ? $_POST['title3'] : '' ;
        $i = $_POST['number'];
        $post = array(
            'id' => $i,
            'image' => $image,
            'url' => $url,
            'title1' => $title1,
            'title2' => $title2,
            'title3' => $title3
        );
        $banner = $this->generalmodel->getBannerById($i);
        if (isset($banner['id']) && $banner['id'] != "") {
            $this->generalmodel->update($post, $i);
            $this->session->set_flashdata('message', 'Đã thay đổi banner thành công!');
        } else {
            $this->generalmodel->add($post);
            $this->session->set_flashdata('message', 'Đã thêm mới banner thành công!');
        }
    }

}